package com.huaqin.punan.headset;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.ArrayList;

public class MainActivity extends Activity {
    public static final String TAG = "HeadsetActionMainActivity";
    private String HeadsetActionServiceName = "com.huaqin.punan.headset.HeadsetActionServices";

    private Button mybtn;
    private TextView mytv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mytv = (TextView)findViewById(R.id.mytv);
        mybtn = (Button)findViewById(R.id.mybtn);

        mybtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this,HeadsetActionServices.class);
                MainActivity.this.startService(intent);

                updateServiceState();
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        updateServiceState();

    }

    @Override
    protected void onStop() {
        super.onStop();

    }

    public void updateServiceState(){
        boolean HeadsetServiceFlag = isServiceWork(HeadsetActionServiceName);

        if(HeadsetServiceFlag){
            mytv.setText("Service is Running!!!");
        }else{
            mytv.setText("Service has Stopped~~");
        }
    }

    public boolean isServiceWork(String mServiceName) {
        ActivityManager myManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList<ActivityManager.RunningServiceInfo> runningService = (ArrayList<ActivityManager.RunningServiceInfo>) myManager
                .getRunningServices(30);
        for (int i = 0; i < runningService.size(); i++) {
            if (runningService.get(i).service.getClassName().toString()
                    .equals(mServiceName)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
}
